import { getDetail } from '@/api/user';
import type { IUser } from '@/typings/interface';
import { delayNavigateTo } from '@/utils/navigator';

export const useUser = defineStore(
  'user',
  () => {
    let isLogin = $ref<boolean>(false);
    let token = $ref<string>('');
    let details = $ref<IUser>();
    // 更改登录状态
    const switchLoginState = async (_token: string) => {
      token = _token;
      isLogin = true;
      await syncUserInfo();
      delayNavigateTo('/pages/home/index');
    };
    // 获取用户信息
    const syncUserInfo = async () => {
      if (!token || !isLogin) return;
      details = (await getDetail()).data;
    };
    // 退出登录
    function logout() {
      token = '';
      isLogin = false;
      details = {} as any;
    }
    return $$({
      isLogin,
      token,
      switchLoginState,
      syncUserInfo,
      details,
      logout
    });
  },
  {
    persist: true
  }
);
